package cn.jhc.teachingquality.net;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Queue;

import cn.jhc.teachingquality.bean.PracticeLog;

/**
 * Created by luyanfei on 16-3-7.
 */
public abstract class TeachingQualityRequest<T> extends Request<T> {

    private Response.Listener<T> listener;

    public TeachingQualityRequest(int method, String url, Response.Listener<T> listener) {
        super(method, url, new DefaultResponseErrorListener());
        this.listener = listener;
    }

//    public TeachingQualityRequest(int method, String url) {
//        this(method, url, null);
//    }

    //使用RequestFuture时，要保证Response.Listener对象为RequestFuture对象。
    public void setListener(Response.Listener<T> listener) {
        this.listener = listener;
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        Document document;
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        document = Jsoup.parse(parsed);
        // handle response
        T handled = handleResponse(document);
        return Response.success(handled, HttpHeaderParser.parseCacheHeaders(response));
    }

    protected abstract T handleResponse(Document document);

    @Override
    protected void deliverResponse(T response) {
        if(listener != null) {
            listener.onResponse(response);
        }
    }
}
